﻿using System;
using System.Threading.Tasks;
using SDCloudSolution.SDCloud.BusinessLayer.Model.Interfaces;
using SDCloudSolution.SDCloud.Entities.Models;
using SDCloudSolution.SDCloud.ModelRunAgent.Infrastructure.Interfaces;

namespace SDCloudSolution.SDCloud.ModelRunAgent.Infrastructure
{
    public class ModelExecutionContextProvider : IModelExecutionContextProvider
    {
        private readonly IModelRunComponent _modelRunComponent;

        public ModelRunEntity CurrentModelRunEntity { get; private set; }

        public ModelExecutionContextProvider(IModelRunComponent modelRunComponent, ModelRunEntity currentModelRunEntity)
        {
            _modelRunComponent = modelRunComponent;
            CurrentModelRunEntity = currentModelRunEntity;
        }

        private async Task UpdateCurrentState()
        {
            CurrentModelRunEntity = await _modelRunComponent.GetByIdAsync(CurrentModelRunEntity.Id);
        }

        public async Task<bool> IsModelRunCanceled()
        {
            await UpdateCurrentState();
            return CurrentModelRunEntity.Status == ModelRunStatus.Canceled;
        }

        public async Task CompleteModelRun()
        {
            await UpdateCurrentState();
            CurrentModelRunEntity.EndDateUtc = DateTime.UtcNow;
            CurrentModelRunEntity.Status = ModelRunStatus.Success;

            await _modelRunComponent.UpdateModelRunAsync(CurrentModelRunEntity);
        }
    }
}
